package com.springSecurity.test.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springSecurity.test.Entity.TbUser;
import com.springSecurity.test.Mapper.TbUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TbUserMapper tbUserMapper;

//    @Autowired
//    private UserMapper userMapper;
    /**
     * 通过查询数据库获取用户名和密码
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TbUser user = tbUserMapper.selectOne(new LambdaQueryWrapper<TbUser>().eq(TbUser::getUsername,s));
        System.out.println("user:"+user);
        if (user==null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //构建认证明细对象
        //获取用户权限
        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles());
        return new User(user.getUsername(),user.getPassword(),list);
    }
//    @Override
//    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName,s));
//        System.out.println("user:"+user);
//        if(Objects.isNull(user)){
//            throw new RuntimeException("用户名或密码错误");
//        }
//        //封装成UserDetails对象返回
//        return new LoginUser(user);
//    }
}
